package com.comum.javahomework420242025.controller;

import com.comum.javahomework420242025.pojo.*;
import com.comum.javahomework420242025.repository.AreaRepository;
import com.comum.javahomework420242025.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class AreaController {
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private UserRepository userRepository;
    @PostMapping("/addArea")
    public Result addArea(@RequestBody Area area){
        System.out.println(area);
        area.setId(null);
        areaRepository.save(area);
        return Result.success();
    }
    @PutMapping("/updateArea")
    public Result updateArea(@RequestBody Area area){
        System.out.println(area);
        areaRepository.save(area);
        return Result.success();
    }
    @PostMapping("/getArea")
    public Result<PageBean<Area>> getArea(@RequestBody AskList askList){
        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        PageBean<Area> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<Area> page = areaRepository.selectByStr(str,pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());
        return Result.success(pb);
    }
    @DeleteMapping("/deleteArea")
    public Result deleteArea(String id){
        System.out.println(id);
        List<User> users = userRepository.findByAreaId(id);
        if(users!=null){
            return Result.error("该片区存在用户！");
        }
        return Result.success();
    }


    @GetMapping("/getAllArea")
    public Result getAllClient()
    {
        return Result.success(areaRepository.findAll());
    }
}
